package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.dto.SensitiveDTO;
import com.andy.blog.admin.dto.TrieNodeDTO;
import com.andy.blog.admin.service.SensitiveBusService;
import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.page.PageUtilsDTO;
import com.andy.blog.common.reponse.BlogResultCode;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.SensitiveDO;
import com.andy.blog.dal.service.SensitiveDalService;
import com.andy.blog.dal.vo.SensitiveVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * Created by andy on 2023/7/21 18:42
 */
@Service
public class SensitiveBusServiceImpl implements SensitiveBusService {

    // 将敏感词替换成 ***
    private static final String REPLACEMENT = "***";

    // 根节点
    private TrieNodeDTO rootNode = new TrieNodeDTO();

    @Resource
    private SensitiveDalService sensitiveDalService;

    /**
     * 初始化前缀树
     */
    @PostConstruct
    public void init() {
        List<SensitiveDTO> sensitiveDTOList = selectList(SensitiveVO.builder().build());
        if (CollectionUtils.isNotEmpty(sensitiveDTOList)) {
            for (SensitiveDTO sensitiveDTO : sensitiveDTOList) {
                // 添加到前缀树
                this.addKeyword(sensitiveDTO.getContent());
            }
        }
    }

    @Override
    public List<SensitiveDTO> selectList(SensitiveVO sensitiveVO) {
        List<SensitiveDO> sensitiveDOS = sensitiveDalService.selectList(sensitiveVO);
        return TransformUtils.transformList(sensitiveDOS, SensitiveDTO.class);
    }

    @Override
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return text;
        }

        // 指针 1：前缀树的工作指针
        TrieNodeDTO tempNode = rootNode;
        // 指针 2：指向文本中某个敏感词的第一位
        int begin = 0;
        // 指针 3；指向文本中某个敏感词的最后一位
        int end = 0;

        // 记录过滤后的文本（结果）
        StringBuilder sb = new StringBuilder();

        while (end < text.length()) {
            char c = text.charAt(end);
            // 跳过符号（防止敏感词混合符号，比如 ☆赌☆博）
            if (isSymbol(c)) {
                // 若指针 1 处于根节点，则将此符号计入结果（直接忽略），让指针 2 向下走一步
                if (tempNode == rootNode) {
                    sb.append(c);
                    begin++;
                }
                // 无论符号在开头还是在中间，指针 3 都会向下走一步
                end++;
                continue;
            }

            // 检查子节点
            tempNode = tempNode.getSubNode(c);
            if (tempNode == null) {
                // 以指针 begin 开头的字符串不是敏感词
                sb.append(text.charAt(begin));
                // 进入下一位的判断
                begin++;
                end = begin;
                // 指针 1 重新指向根节点
                tempNode = rootNode;
            } else if (tempNode.isKeywordEnd()) {
                // 发现敏感词，将 begin~end 的字符串替换掉
                sb.append(REPLACEMENT);
                // 进入下一位的判断
                end++;
                begin = end;
                // 指针 1 重新指向根节点
                tempNode = rootNode;
            } else {
                // 检查下一个字符
                end++;
            }
        }

        // 将最后一批字符计入结果（如果最后一次循环的字符串不是敏感词，上述的循环逻辑不会将其加入最终结果）
        sb.append(text.substring(begin));

        return sb.toString();
    }

    @Override
    public PageUtilsDTO<SensitiveDTO> selectPage(SensitiveVO sensitiveVO) {
        IPage<SensitiveDO> sensitiveDOIPage = sensitiveDalService.selectPage(sensitiveVO);
        return PageUtilsDTO.build(sensitiveDOIPage.getTotal(), TransformUtils.transformList(sensitiveDOIPage.getRecords(), SensitiveDTO.class));
    }

    @Override
    public void add(SensitiveVO sensitiveVO) {

        if (Objects.isNull(sensitiveVO) || StringUtils.isBlank(sensitiveVO.getContent())) {
            throw new BlogServiceException(BlogResultCode.BLOG_000001, "入参不能为空");
        }

        SensitiveDO sensitiveDO = sensitiveDalService.selectOne(sensitiveVO);
        if (Objects.nonNull(sensitiveDO)) {
            throw new BlogServiceException(BlogResultCode.BLOG_000001, "该词汇已存在,请勿重复添加");
        }

        sensitiveDalService.insertData(sensitiveVO);
    }

    @Override
    public SensitiveDTO selectById(Long id) {
        SensitiveDO sensitiveDO = sensitiveDalService.selectById(id);
        return TransformUtils.transform(sensitiveDO, SensitiveDTO.class);
    }

    @Override
    public void updateById(SensitiveVO sensitiveVO) {
        sensitiveDalService.updateData(sensitiveVO);
    }

    @Override
    public void deleteById(Long id) {
        sensitiveDalService.deleteById(id);
    }

    @Override
    public void refreshSensitive() {
        rootNode = new TrieNodeDTO();
        init();
    }

    /**
     * 将一个敏感词添加进前缀树中
     **/
    private void addKeyword(String keyword) {
        TrieNodeDTO tempNode = rootNode;
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            TrieNodeDTO subNode = tempNode.getSubNode(c);// 首先判断是否存在相同子节点

            if (subNode == null) {
                subNode = new TrieNodeDTO(); // 初始化子节点
                tempNode.addSubNode(c, subNode); // 添加子节点
            }

            // 指向子节点，进入下一层循环
            tempNode = subNode;

            // 设置结束标识（叶子节点），表示这个字符是该敏感词的最后一个字符
            if (i == keyword.length() - 1) {
                tempNode.setKeywordEnd(true);
            }
        }
    }

    /**
     * 判断某个字符是否是符号
     */
    private boolean isSymbol(Character c) {
        // 0x2E80~0x9FFF 是东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }
}
